Page({

  /**
   * 页面的初始数据
   */
  data: {
    users: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.getUsers()
  },

  /**
   * 获取用户
   */
  getUsers: function(e) {
    wx.showLoading({
      title: '',
    })
    let that = this
    const db = wx.cloud.database()
    db.collection('users').get({
      success(res) {
        console.log(res)
        if(res.data.length==0){
          wx.hideLoading()
        }
        let users = res.data
        for (let i = 0; i < users.length; i++) {
          db.collection('records').where({
            userid: users[i].userid
          }).count({
            success(res) {
              let total = res.total
              db.collection('users').doc(users[i]._id).update({
                data: {
                  days: total
                },
                success(res){
                  db.collection('users').orderBy('days', 'desc').limit(10).get({
                    success(res) {
                      console.log(res)
                      that.setData({
                        users: res.data
                      })
                      wx.hideLoading()
                    }
                  })
                },
                fail: console.error
              })
            }
          })
        }
      }
    })
  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})